package com.frank.oss.adapter;

import com.frank.oss.eneity.FileInfo;
import com.frank.oss.util.MinioUtil;
import lombok.SneakyThrows;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.InputStream;
import java.util.List;

/**
 * @author Frank Zou
 * @version v0.0.1
 * @date 2024/2/1 22:26
 * @description
 */
public class MinioStorageAdapter implements StorageAdapter {

    @Resource
    private  MinioUtil minioUtil;

    /**
     * minioUrl
     */
    @Value("${spring.storage.minio.url}")
    private String url;


    @Override
    public void createBucket(String bucketName) throws Exception {
        minioUtil.createBucket(bucketName);
    }

    @Override
    public void uploadFile(MultipartFile multipartFile, String bucketName, String objectName) throws Exception {
        minioUtil.createBucket(bucketName);
        if (StringUtils.isNotBlank(objectName)) {
            minioUtil.uploadFile(multipartFile.getInputStream(), bucketName, objectName + "/" + multipartFile.getOriginalFilename());
        } else {
            minioUtil.uploadFile(multipartFile.getInputStream(), bucketName, multipartFile.getOriginalFilename());
        }

    }

    @Override
    public List<String> listBuckets() throws Exception {
        return minioUtil.listBuckets();
    }

    @Override
    public List<FileInfo> getAllObjects(String bucketName) throws Exception { 
        return minioUtil.getAllObjects(bucketName);
    }

    @Override
    public InputStream download(String bucket, String objectName) throws Exception {
        return minioUtil.download(bucket, objectName);
    }

    @Override
    public void deleteBucket(String bucketName) throws Exception {
        minioUtil.deleteBucket(bucketName);
    }

    @Override
    public void deleteObject(String bucketName, String objectName) throws Exception {
        minioUtil.deleteObject(bucketName, objectName);
    }

    @Override
    @SneakyThrows
    public String getUrl(String bucket, String objectName) {
        return url + "/" + bucket + "/" + objectName;
    }
}
